/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufc.great.ad.DAO;

import br.ufc.great.ad.Model.DB;
import br.ufc.great.ad.Model.User;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author great
 */
public class UserDAO {

    DB db = new DB();
    Session session = db.getSession();

    public User getUser(User user) {
        Query query = (Query) session.createQuery("from User");
        List listUsers = query.list();

        Iterator it = listUsers.iterator();

        while (it.hasNext()) {

            User userCurrent = (User) it.next();
            if (userCurrent.getLogin().equals(user.getLogin())
                    && userCurrent.getPass().equals(user.getPass())) {

                return userCurrent;

            }
        }
        return null;
    }

    public void addUser(User user) {
        Transaction tx = (Transaction) session.beginTransaction();
        session.save(user);
        tx.commit();
    }
    
    public User editUser(User userToEdit){
        User userBD = getUser(userToEdit);
        
        if(userBD == null){
            return null;
        }
        else{
            Transaction tx = (Transaction) session.beginTransaction();    
            userBD.setName(userToEdit.getName());
            userBD.setEmail(userToEdit.getEmail());
            userBD.setLogin(userToEdit.getLogin());
            userBD.setPass(userToEdit.getPass());
            session.update(userBD);
            tx.commit();
            return userToEdit;
        }
    }
}
